# -*- coding: utf-8 -*-

from time import sleep
from random import random
from threading import (
    Thread,
    Lock,
    enumerate,

)

from py_example.design_pattern.singleton_pattern import get_instance

import logging

logger = logging.getLogger(__name__)


class ExtendsThread(Thread):
    """继承线程方式创建线程"""

    def __init__(self, delay: float, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
        super().__init__(group=group, target=target, name=name,
                         args=args, kwargs=kwargs, daemon=daemon)
        self.delay = delay
        pass

    def run(self) -> None:
        logger.info('start')
        sleep(self.delay)
        logger.info('delay:%f', self.delay)
        pass


def target_function(delay: float):
    """目标函数方式创建线程"""
    logger.info('start')
    sleep(delay)
    logger.info('delay:%f', delay)

    pass


def create_thread():
    """创建线程的两种方式"""
    logger.info('start')
    # 实例化继承线程类对象
    thread = ExtendsThread(random(), name='ExtendsThread', )
    thread.start()

    logger.info('start')

    # 以目标函数作为参数创建线程
    thread = Thread(target=target_function, args=(random(),), name='thread-name', )
    thread.start()

    logger.info('stop')
    pass


def thread_count():
    """统计当前存在线程总数"""
    while True:
        # 当前线程数量
        length = len(enumerate())
        logger.info('current thread count:%d' % length)
        if length <= 1:
            # 最后一个线程跳出结束循环
            break

        # 延时
        sleep(1)

    pass


def target_method1(args):
    """目标函数"""
    logger.info('start:%s' % args)
    global num
    for j in range(1000000):
        # 默认True阻塞
        if lock.acquire(blocking=True):
            num += 1
            lock.release()
            pass
        pass

    logger.info(num)

    pass


def target_method2():
    """目标函数"""
    global num
    for j in range(1000000):
        # 默认True阻塞
        if lock.acquire(blocking=True):
            num += 1
            lock.release()

    logger.info(num)
    pass


# 全局变量
num = 0


# 创建互斥锁，默认未上锁

#
#
# def synchronous():
#     """线程使用全局变量（线程共享变量同步）"""
#
#     # 以目标函数作为参数创建线程
#     thread1 = threading.Thread(target=target_method1, args=('params',))
#     thread1.start()
#
#     thread2 = threading.Thread(target=target_method2)
#     thread2.start()
#
#     print('%s:%s' % (threading.currentThread().getName(), num,))
#
#     pass


class ThreadPool(object):
    """
    线程池
    """
    lock = Lock()  # 线程锁

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        return get_instance(cls, cls.lock, object.__new__(cls))

    def __del__(self):
        pass


if __name__ == '__main__':
    lock = Lock()

    create_thread()

    pass
